package com.example.demo.entity;

import com.example.demo.listener.HashChainEntityListener;
import jakarta.persistence.*;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 订单实体类，继承哈希链基础类以实现防篡改功能
 */
@Entity
@Table(name = "orders")
//@EntityListeners(HashChainEntityListener.class)
@Getter
@Setter
@Data
public class Order extends HashChainEntity {

    @Id
    private Long id;

    @Column(name = "order_no", nullable = false, unique = true)
    private String orderNo;
//    @Column(name = "product_id", nullable = false)
//    private Long productId;
//    @Column(name = "product_name", nullable = false)
//    private String productName;
//    @Column(name = "product_price", nullable = false)
//    private BigDecimal productPrice;
//    @Column(name = "product_description")
//    private String productDescription;
////数量
//@Column(name = "quantity", nullable = false)
//private Integer quantity;
    @Column(name = "payment_method")
    private String paymentMethod;
    @Column(name = "payment_status")
    private int paymentStatus;// 1:待支付, 2:已支付, 3:已取消

    @Column(name = "currency", nullable = false)
    private String currency;

    @Column(name = "amount", nullable = false)
    private BigDecimal amount;

    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;
    @Column(name = "current_version", nullable = false)
    private long currentVersion;
    @Column(name = "user_id", nullable = false)
    private long userId;
    @Column(name = "user_name", nullable = false)
    private String userName;

    public int updateFrom(Order updatedOrder) {
        if (updatedOrder == null) {
            return -1;
        }
        if(updatedOrder.id == null)
            return -2;
        if (!Objects.equals(this.id, updatedOrder.id))
            return -3;

        if (updatedOrder.amount == null)
            return -4;
        this.amount = updatedOrder.amount;

        return 0;
    }

    /**
     * 获取用于计算哈希的核心业务字段
     */
    public SortedMap<String, Object> getCoreFields() {
        SortedMap<String, Object> coreFields = new TreeMap<>();
        coreFields.put("id", this.id);
        coreFields.put("userId", this.userId);
        coreFields.put("orderNo", this.orderNo);
        coreFields.put("amount", this.amount);
        coreFields.put("paymentStatus", this.paymentStatus);
        coreFields.put("updateTimestamp", this.getUpdateTimestamp());
        return coreFields;
    }

    public Order() {
        super();
        this.currentVersion = 1L;
    }
}
